<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/3/17
 * Time: 20:33
 */

namespace App\Helpers\Api;


use Illuminate\Support\Facades\Redis;

trait CacheTrait
{
    public static function create($data = null)
    {
        if ($data == null) {
            return null;
        }
        $instance = new static;
        foreach ($data as $key => $value) {
            $instance[$key] = $value;
        }
        return $instance;
    }

    /**
     * 如果方法是 find($id, $nocache)
     *
     * @param  string $method
     * @param  array $parameters
     * @return mixed
     */
    public static function __callStatic($method, $parameters)
    {
        if ($method == 'find') {
            // 从缓存中获取数据
            $obj = static::create(json_decode(Redis::get(static::getCacheKey($parameters[0])), true));
            if (null == $obj) {
                $obj = (new static)->$method(...$parameters);
                if (null == $obj) {
                    return null;
                } else {
                    $key = static::getCacheKey($parameters[0]);
                    // 设置缓存及过期时间
                    Redis::set($key, $obj);
                    Redis::expire($key, static::$expire_time);
                    return $obj;
                }
            } else {
                $obj->exists = true;
                return $obj;
            }
        } else if ($method == 'findNoCache') {
            $method = 'find';
            return (new static)->$method(...$parameters);
        }

        return (new static)->$method(...$parameters);
    }

    private static function getCacheKey($id)
    {
        $name = str_replace('\\', ':', __CLASS__);
        return "{$name}:{$id}";
    }

    private static function clearCache($id){
        Redis::del(self::getCacheKey($id));
    }


    public function save(array $options = []){
        static::clearCache($this[$this->primaryKey]);
        return parent::save($options);
    }

}